package com.tanhua.manage.service;




import cn.hutool.crypto.SecureUtil;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.model.db.Admin;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.PageResult;


import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import java.util.List;
import java.util.Map;

@Service
public class ManageLoginService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AdminMapper adminMapper;

   @DubboReference
   private UserLocationApi userLocationApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    public String loginVerification(String username, String password, String verificationCode, String uuid) {
        //1.验证码校验
        String key= Constants.CAP_CODE+uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)){
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key);
        //2.根据用户名查询该用户是否存在
        QueryWrapper<Admin> qw=new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //判断admin是否存在.若存在比较密码是否一致
        //对密码加密
        password= SecureUtil.md5(password);
        if (admin==null || !password.equals(admin.getPassword())){
            throw new BusinessException("用户名或密码错误");
        }
        //生成token
        Map map=new HashMap();
        map.put("id",admin.getId());
        map.put("username",admin.getUsername());
        String token = JwtUtils.getToken(map);
        return token;

    }

    public PageResult findAll(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage=userInfoApi.findAll(page,pagesize);

        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    public List<String> findLocation(String userId) {
        List<String> list=userLocationApi.findByUserId(userId);
        if (list==null){
            throw new BusinessException("暂无位置信息");
        }
        return list;
    }
}
